package com.knowledgegraph.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.knowledgegraph.common.Result;
import com.knowledgegraph.entity.EntityType;
import com.knowledgegraph.service.EntityTypeService;
import com.knowledgegraph.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 实体类型管理控制器
 * 
 * @author system
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/entity-types")
public class EntityTypeController {

    @Autowired
    private EntityTypeService entityTypeService;

    /**
     * 分页查询实体类型列表
     */
    @PostMapping("/list")
    public Result<Map<String, Object>> getEntityTypes(@RequestBody Map<String, Object> params) {
        
        int page = (Integer) params.getOrDefault("page", 1);
        int pageSize = (Integer) params.getOrDefault("pageSize", 10);
        String searchText = (String) params.get("searchText");
        
        try {
            log.info("查询实体类型列表 - page: {}, pageSize: {}, searchText: {}", 
                    page, pageSize, searchText);
            
            // 构建分页对象
            Page<EntityType> pageObj = new Page<>(page, pageSize);
            
            // 构建查询参数
            Map<String, Object> queryParams = new HashMap<>();
            queryParams.put("searchText", searchText);
            
            // 执行分页查询
            IPage<EntityType> result = entityTypeService.getEntityTypesWithPagination(pageObj, queryParams);
            
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("data", result.getRecords());
            data.put("total", result.getTotal());
            data.put("current", result.getCurrent());
            data.put("pageSize", result.getSize());
            
            return Result.success(data);
            
        } catch (Exception e) {
            log.error("查询实体类型列表失败", e);
            return Result.error("查询实体类型列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有启用的实体类型
     */
    @PostMapping("/enabled")
    public Result<List<EntityType>> getEnabledEntityTypes() {
        try {
            log.info("获取所有启用的实体类型");
            
            List<EntityType> types = entityTypeService.getEnabledEntityTypes();
            
            return Result.success(types);
            
        } catch (Exception e) {
            log.error("获取启用的实体类型失败", e);
            return Result.error("获取启用的实体类型失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户的实体类型列表
     */
    @PostMapping("/user-types")
    public Result<List<EntityType>> getUserEntityTypes() {
        try {
            Long currentUserId = SecurityUtil.getCurrentUserId();
            log.info("获取用户的实体类型列表 - 用户ID: {}", currentUserId);
            
            List<EntityType> types = entityTypeService.getUserEntityTypes(currentUserId);
            
            return Result.success(types);
            
        } catch (Exception e) {
            log.error("获取用户的实体类型列表失败", e);
            return Result.error("获取用户的实体类型列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取实体类型详情
     */
    @PostMapping("/detail")
    public Result<EntityType> getEntityTypeById(@RequestBody Map<String, Object> params) {
        Long id = Long.valueOf(params.get("id").toString());
        try {
            log.info("获取实体类型详情 - id: {}", id);
            
            EntityType entityType = entityTypeService.getById(id);
            if (entityType == null) {
                return Result.error("实体类型不存在，ID: " + id);
            }
            
            return Result.success(entityType);
            
        } catch (Exception e) {
            log.error("获取实体类型详情失败", e);
            return Result.error("获取实体类型详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建实体类型
     */
    @PostMapping("/create")
    public Result<EntityType> createEntityType(@RequestBody @Valid EntityType entityType) {
        try {
            log.info("创建实体类型 - name: {}, typeCode: {}", entityType.getTypeName(), entityType.getTypeCode());
            
            // 使用当前登录用户ID
            Long currentUserId = SecurityUtil.getCurrentUserId();
            boolean success = entityTypeService.createEntityType(entityType, currentUserId);
            
            if (success) {
                return Result.success("创建成功", entityType);
            } else {
                return Result.error("创建失败");
            }
            
        } catch (Exception e) {
            log.error("创建实体类型失败", e);
            return Result.error("创建实体类型失败: " + e.getMessage());
        }
    }

    /**
     * 更新实体类型
     */
    @PostMapping("/update")
    public Result<EntityType> updateEntityType(@RequestBody Map<String, Object> params) {
        
        Long id = Long.valueOf(params.get("id").toString());
        @SuppressWarnings("unchecked")
        Map<String, Object> entityTypeData = (Map<String, Object>) params.get("entityType");
        
        EntityType entityType = new EntityType();
        entityType.setId(id);
        entityType.setTypeName((String) entityTypeData.get("typeName"));
        entityType.setTypeCode((String) entityTypeData.get("typeCode"));
        entityType.setDescription((String) entityTypeData.get("description"));
        entityType.setColor((String) entityTypeData.get("color"));
        //entityType.setIcon((String) entityTypeData.get("icon"));
        entityType.setSortOrder(Integer.valueOf(entityTypeData.get("sortOrder").toString()));
        entityType.setEnabled((Boolean) entityTypeData.get("enabled"));
        
        try {
            log.info("更新实体类型 - id: {}, name: {}, typeCode: {}", id, entityType.getTypeName(), entityType.getTypeCode());
            
            // 先检查实体类型是否存在
            EntityType existingType = entityTypeService.getById(id);
            if (existingType == null) {
                return Result.error("实体类型不存在，ID: " + id);
            }
            
            // 使用当前登录用户ID
            Long currentUserId = SecurityUtil.getCurrentUserId();
            boolean success = entityTypeService.updateEntityType(entityType, currentUserId);
            
            if (success) {
                // 返回更新后的实体类型
                EntityType updatedType = entityTypeService.getById(id);
                return Result.success("更新成功", updatedType);
            } else {
                return Result.error("更新失败");
            }
            
        } catch (Exception e) {
            log.error("更新实体类型失败", e);
            return Result.error("更新实体类型失败: " + e.getMessage());
        }
    }

    /**
     * 删除实体类型
     */
    @PostMapping("/delete")
    public Result<Void> deleteEntityType(@RequestBody Map<String, Object> params) {
        Long id = Long.valueOf(params.get("id").toString());
        try {
            log.info("删除实体类型 - id: {}", id);
            
            // 使用当前登录用户ID
            Long currentUserId = SecurityUtil.getCurrentUserId();
            boolean success = entityTypeService.deleteEntityType(id, currentUserId);
            
            if (success) {
                return Result.success("删除成功", null);
            } else {
                return Result.error("删除失败");
            }
            
        } catch (Exception e) {
            log.error("删除实体类型失败", e);
            return Result.error("删除实体类型失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除实体类型
     */
    @PostMapping("/batch-delete")
    public Result<Void> batchDeleteEntityTypes(@RequestBody Map<String, Object> params) {
        @SuppressWarnings("unchecked")
        List<Long> ids = (List<Long>) params.get("ids");
        try {
            log.info("批量删除实体类型 - ids: {}", ids);
            
            // 使用当前登录用户ID
            Long currentUserId = SecurityUtil.getCurrentUserId();
            boolean success = entityTypeService.batchDeleteEntityTypes(ids, currentUserId);
            
            if (success) {
                return Result.success("批量删除成功", null);
            } else {
                return Result.error("批量删除失败");
            }
            
        } catch (Exception e) {
            log.error("批量删除实体类型失败", e);
            return Result.error("批量删除实体类型失败: " + e.getMessage());
        }
    }

    /**
     * 更新排序序号
     */
    @PostMapping("/update-sort-order")
    public Result<Void> updateSortOrder(@RequestBody Map<String, Object> params) {
        Long id = Long.valueOf(params.get("id").toString());
        Integer sortOrder = Integer.valueOf(params.get("sortOrder").toString());
        
        try {
            log.info("更新实体类型排序 - id: {}, sortOrder: {}", id, sortOrder);
            
            boolean success = entityTypeService.updateSortOrder(id, sortOrder);
            
            if (success) {
                return Result.success("更新排序成功", null);
            } else {
                return Result.error("更新排序失败");
            }
            
        } catch (Exception e) {
            log.error("更新实体类型排序失败", e);
            return Result.error("更新实体类型排序失败: " + e.getMessage());
        }
    }

    /**
     * 启用/禁用实体类型
     */
    @PostMapping("/toggle-enabled")
    public Result<Void> toggleEnabled(@RequestBody Map<String, Object> params) {
        Long id = Long.valueOf(params.get("id").toString());
        Boolean enabled = (Boolean) params.get("enabled");
        
        try {
            log.info("切换实体类型状态 - id: {}, enabled: {}", id, enabled);
            
            boolean success = entityTypeService.toggleEnabled(id, enabled);
            
            if (success) {
                return Result.success(enabled ? "启用成功" : "禁用成功", null);
            } else {
                return Result.error(enabled ? "启用失败" : "禁用失败");
            }
            
        } catch (Exception e) {
            log.error("切换实体类型状态失败", e);
            return Result.error("切换实体类型状态失败: " + e.getMessage());
        }
    }

    /**
     * 检查类型代码是否已存在
     */
    @PostMapping("/check-code")
    public Result<Boolean> checkTypeCode(@RequestBody Map<String, Object> params) {
        String typeCode = (String) params.get("typeCode");
        Long excludeId = params.get("excludeId") != null ? Long.valueOf(params.get("excludeId").toString()) : null;
        
        try {
            log.info("检查类型代码是否存在 - typeCode: {}, excludeId: {}", typeCode, excludeId);
            
            boolean exists = entityTypeService.isTypeCodeExists(typeCode, excludeId);
            
            return Result.success(exists);
            
        } catch (Exception e) {
            log.error("检查类型代码是否存在失败", e);
            return Result.error("检查类型代码是否存在失败: " + e.getMessage());
        }
    }
}